<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="药品名称" style="width: 480px" prop="medicineId">
          <el-select v-model="queryParams.medicineId" placeholder="请选择药品名称" clearable>
            <el-option v-for="medicine in medicineList" :key="medicine.id" :label="medicine.shortNameBrandPackaging" :value="medicine.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库编号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入入库编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="使用状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="请选择使用状态" clearable>
            <el-option v-for="dict in used_state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['health:medicineStockIn:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:medicineStockIn:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['health:medicineStockIn:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading" height="calc(100% - 0.65rem)">
        <el-table v-loading="loading" :data="medicineStockInList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="药品名称" align="center" prop="medicineName" />
          <el-table-column label="购买时间" align="center" prop="purchaseDate" width="155"> </el-table-column>
          <el-table-column label="入库数量" align="center" width="100" prop="quantity" />
          <el-table-column label="包装单位" align="center" width="100" prop="packageUnit">
            <template #default="scope">
              <dict-tag :options="package_unit" :value="scope.row.packageUnit" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="单价（元）" align="center" width="100" prop="purchasePrice" />
          <el-table-column label="总价（元）" align="center" width="100" prop="totalPrice" /> -->
          <el-table-column label="入库编号" align="center" width="150" prop="code" />
          <el-table-column label="使用状态" align="center" width="100" prop="state">
            <template #default="scope">
              <dict-tag :options="used_state" :value="scope.row.state" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="生产日期" align="center" prop="productionDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="过期日期" align="center" prop="expiringDate" width="120">
            <template #default="scope">
              <span>{{ parseTime(scope.row.expiringDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格总数" align="center" width="100" prop="totalCount" />
          <!-- <el-table-column label="使用数量" align="center" width="100" prop="usedCount" /> -->
          <el-table-column label="剩余数量" align="center" width="100" prop="leftCount" />
          <el-table-column label="规格单位" align="center" width="100" prop="unit">
            <template #default="scope">
              <dict-tag :options="medical_unit" :value="scope.row.unit" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改药品入库清单对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="medicineStockInRef" :inline="true" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="治疗类型" prop="marType">
          <el-select v-model="form.marType" placeholder="请选择治疗类型" @change="handleMarTypeChange" clearable>
            <el-option v-for="dict in mar_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="药品名称" prop="medicineId">
          <el-select v-model="form.medicineId" placeholder="请选择药品名称" @change="handleMedicineChange" clearable>
            <el-option v-for="medicine in medicineList" :key="medicine.id" :label="medicine.shortNameBrandPackaging" :value="medicine.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入入库编号" />
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input @change="handleQuantityChange" v-model="form.quantity" type="number" placeholder="请输入入库数量"> </el-input>
        </el-form-item>
        <el-form-item label="购买时间" prop="purchaseDate">
          <el-date-picker clearable v-model="form.purchaseDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择购买时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择使用状态">
            <el-option v-for="dict in used_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择生产日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="过期日期" prop="expiringDate">
          <el-date-picker clearable v-model="form.expiringDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择过期日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="包装单位" prop="packageUnit">
          <el-select v-model="form.packageUnit" placeholder="请选择包装单位">
            <el-option v-for="dict in package_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格总数" prop="totalCount">
          <el-input v-model="form.totalCount" type="number" readonly placeholder="请输入规格总数"> </el-input>
        </el-form-item>
        <el-form-item label="规格单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择规格单位">
            <el-option v-for="dict in medical_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已使用数量" prop="usedCount">
          <el-input v-model="form.usedCount" type="number" placeholder="请输入已使用数量"> </el-input>
        </el-form-item>
        <el-form-item label="剩余数量" prop="leftCount">
          <el-input v-model="form.leftCount" type="number" placeholder="请输入剩余数量"> </el-input>
        </el-form-item>
        <el-form-item label="年龄体重" prop="ageWeight">
          <el-input v-model="form.ageWeight" placeholder="请输入年龄体重" />
        </el-form-item>
        <el-form-item label="药品单价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" type="number" placeholder="请输入药品单价">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="药品总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" type="number" placeholder="请输入药品总价">
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="医嘱" style="width: 792px" prop="usage">
          <el-input v-model="form.usage" placeholder="请输入医嘱" />
        </el-form-item>
        <el-form-item label="购买地址" style="width: 792px" prop="purchaseAddress">
          <el-input v-model="form.purchaseAddress" placeholder="请输入购买地址" />
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看药品入库清单'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MedicineStockIn">
import { listMedicineStockIn, getMedicineStockIn, delMedicineStockIn, addMedicineStockIn, updateMedicineStockIn } from '@/api/health/medicineStockIn'
// eslint-disable-next-line no-unused-vars
import { listMedicineBasic, getMedicineBasic } from '@/api/health/medicineBasic'
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { used_state, package_unit, medical_unit, mar_type } = proxy.useDict('used_state', 'package_unit', 'medical_unit', 'mar_type')

const medicineStockInList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const medicineList = ref([])
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['health:medicineStockIn:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:medicineStockIn:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:medicineStockIn:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    medicineId: null,
    quantity: null,
    productionDate: null,
    expiringDate: null,
    purchaseDate: null,
    purchasePrice: null,
    code: null,
    state: null,
    leftCount: null,
    usedCount: null,
    purchaseAddress: null
  },
  queryMedicineParams: {
    pageNum: 1,
    pageSize: 1000
  },
  rules: {
    medicineId: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
    quantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
    productionDate: [{ required: true, message: '生产日期不能为空', trigger: 'blur' }],
    expiringDate: [{ required: true, message: '过期日期不能为空', trigger: 'blur' }],
    //purchaseDate: [{ required: true, message: '购买日期不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
    state: [{ required: true, message: '使用状态不能为空', trigger: 'change' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const { queryParams, form, rules, queryMedicineParams } = toRefs(data)

const handleQuantityChange = (val) => {
  if (form.value.medicineId != null) {
    getMedicineBasic(form.value.medicineId).then((response) => {
      form.value.totalCount = response.data.specifications * val
    })
  }
}
const handleMarTypeChange = (val) => {
  queryMedicineParams.value.treatmentType = val
  form.value.medicineName = ''
  form.value.name = ''
  form.value.medicineId = null
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}

const handleMedicineChange = (medicineId) => {
  getMedicineBasic(medicineId).then((response) => {
    form.value.packageUnit = response.data.packageUnit
    form.value.unit = response.data.unit
    form.value.totalCount = response.data.specifications
    if (form.value.quantity != null) {
      form.value.totalCount = response.data.specifications * form.value.quantity
    }
  })
}

/** 查询药品入库清单列表 */
function getList() {
  loading.value = true
  listMedicineStockIn(queryParams.value).then((response) => {
    medicineStockInList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询药品管理列表 */
function getMedicineList() {
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    medicineId: null,
    quantity: 1,
    productionDate: null,
    expiringDate: null,
    purchaseDate: null,
    purchasePrice: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    code: null,
    state: null,
    leftCount: null,
    usedCount: null,
    purchaseAddress: null,
    totalPrice: null,
    usage: null,
    ageWeight: null,
    totalCount: null,
    unit: null,
    packageUnit: null
  }
  proxy.resetForm('medicineStockInRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看药品入库清单'
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  const date = new Date()
  const year = date.getFullYear() // 年份
  let month = date.getMonth() + 1 // 月份，返回值为0-11，所以需要加1
  let day = date.getDate() // 日期
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  // 对月份和日期进行补零
  month = month < 10 ? '0' + month : month.toString()
  day = day < 10 ? '0' + day : day.toString()
  hour = hour < 10 ? '0' + hour : hour.toString()
  minute = minute < 10 ? '0' + minute : minute.toString()
  second = second < 10 ? '0' + second : second.toString()
  const currentDate = year + month + day + hour + minute + second
  form.value.code = currentDate
  title.value = '添加药品入库清单'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMedicineStockIn(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改药品入库清单'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.medicineStockInRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateMedicineStockIn(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addMedicineStockIn(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delMedicineStockIn(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'health/medicineStockIn/export',
    {
      ...queryParams.value
    },
    `medicineStockIn_${new Date().getTime()}.xlsx`
  )
}

getList()
getMedicineList()
</script>
